use sea_orm::{ActiveModelTrait, EntityTrait};
use crate::db::connector::get_connection;
use crate::error::AppError;

pub async fn one<Entity, ActiveModel, Model>(
    db_identifier: &str,
    active_model: ActiveModel,
) -> crate::error::Result<Model, AppError>
where
    Entity: EntityTrait<Model = Model>,
    ActiveModel: ActiveModelTrait<Entity = Entity> + Send + 'static + sea_orm::ActiveModelBehavior,
    Model: Send + 'static + sea_orm::IntoActiveModel<ActiveModel>,
{
    let db = get_connection(db_identifier)?;
    let res = active_model.insert(&db).await;
    match res {
        Ok(model) => Ok(model),
        Err(e) => Err(AppError::Custom(format!(
            "Failed to create record: {:?}",
            e
        ))),
    }
}